package com.qf.smsplatform.interfaces.controller;

import com.qf.smsplatform.common.exception.SmsPlatfromEx;
import com.qf.smsplatform.common.util.R;
import com.qf.smsplatform.interfaces.form.SmsInterfaceForm;
import com.qf.smsplatform.interfaces.service.InterfaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: LeeRui
 * 2021/1/26 下午 7:48
 **/
@RestController
public class InterfaceController {

    //引入Git配置文件中请求头的各个字段用于获取隐藏的客户端请求ip
    @Value("${ip-header}")
    private String ipHeader;

    //通过Spring工厂注入InterfaceService
    @Autowired
    private InterfaceService interfaceService;

    @PostMapping("/smsInterface")
    public R smsInterface(SmsInterfaceForm smsInterfaceForm, HttpServletRequest request) {
        //通过HttpServletRequest请求获取用户请求时携带的ip地址信息
        String ip = this.getIpAdress(request);

        //将ip地址封装到form对象中
        smsInterfaceForm.setIp(ip);

        try {
            //调用Service，对参数进行校验
            interfaceService.checkParamters(smsInterfaceForm);
            //无异常，正常返回数据
            return R.ok("接收成功！");
        } catch (SmsPlatfromEx spe) { //抛出了自定义异常
            if (spe.getCode() == 105 && spe.getData() != null) {  //说明验证手机号码失败，有错误的手机号码信息需要返回给用户
                return R.errorData(spe);
            } else {  //其它信息验证失败
                return R.error(spe);
            }
        }
    }

    //从用户请求中获取ip
    private String getIpAdress(HttpServletRequest request) {
        //校验ip_header是否使用@Value注入成功
        if (!StringUtils.isEmpty(ipHeader) && ipHeader.length() > 0) {
            //用逗号分隔开ip_header的请求头参数
            String[] headers = ipHeader.split(",");

            //遍历请求头参数数组
            for (String header : headers) {
                //通过request对象从请求头中获取ip
                String ip = request.getHeader(header);

                //判断请求头中是否获取到请求ip
                if (!StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
                    //返回获取到的ip
                    return ip;
                }
            }
        }
        //若未从请求头中获取到ip，则使用传统方法获取并返回
        return request.getRemoteAddr();
    }

}
